/*
 * 
 */

package com.rodirod.vrmonitor;

import java.util.List;
import java.util.Map;

import com.rodirod.vrmonitor.R;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.ConditionVariable;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.text.format.DateUtils;
import android.util.Log;

/**
 * This class supervise a regate and notify in case of Alarm
 */
public class SupervisionService extends Service implements Constants {
    
	private static final String TAG = "SupervisionService";

    // variable which controls the notification thread 
    private ConditionVariable mCondition;
    
    @Override
    public void onCreate() {
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        
        // Start up the thread running the service.  Note that we create a
        // separate thread because the service normally runs in the process's
        // main thread, which we don't want to block.
        Thread notifyingThread = new Thread(null, mTask, "SupervisionService");
        mCondition = new ConditionVariable(false);
        notifyingThread.start();
    }

    @Override
    public void onDestroy() {
        // Stop the thread from generating further notifications
        mCondition.open();
    }

    private Runnable mTask = new Runnable() {
        public void run() {
        	while(!mCondition.block(I_TIMER_PERIOD_MN * 60000)) {
        		Log.v(TAG, "SupervisionService executed at " + DateUtils.formatDateTime(getBaseContext(),System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME));
	            // do the job
        		RaceManager mRM = RaceManager.getInstance();
        		List<Map<String, Object>> listRegates = mRM.getAdapterViewData();
        		
        		int idNotification = 1;
        		for (int ilist=0 ; ilist < listRegates.size() ; ilist++) {
        	    	Map<String,Object> data = listRegates.get(ilist);
        			RaceInfo mRI = (RaceInfo)data.get(M_REGATE_INFO);
        			mRI.readDataFromUrl();
        			int alarmStatus = mRI.updateAlarmStates();
        			if (alarmStatus==I_ALARM_ON) {
                		showNotification(R.drawable.monitored,(String)data.get(M_REGATE_NAME),idNotification);
        			}
        			idNotification++;
        		}
        	}
        	// Done with our work...  stop the service!
           SupervisionService.this.stopSelf();
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    
    private void showNotification(int moodId, String regateName, int notificationID) {

        // Create the new notification
        Notification notification = new Notification(moodId, regateName, System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        Intent intent = new Intent(this, RaceDetailedViewActivity.class);
        intent.putExtra(M_EXTRA_REGATE_NAME, regateName);
        intent.putExtra(M_EXTRA_NOTIFICATION_ID, notificationID);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
 
        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getString(getApplication().getApplicationInfo().labelRes),regateName, contentIntent);

        // Send the notification.
        mNM.notify(notificationID, notification);
    }

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new Binder() {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply,
                int flags) throws RemoteException {
            return super.onTransact(code, data, reply, flags);
        }
    };

    private NotificationManager mNM;
}
